<template>
  <div class="roc-icon-select">
    <el-popover placement="bottom-start" :width="700" trigger="click">
      <template #reference>
        <!-- 选择图标回显 -->
        <el-input :model-value="props.modelValue" placeholder="点击选择图标" readonly>
          <template #prefix>
            <template v-if="props.modelValue">
              <!-- renderIcon 解决字体图标为重新渲染问题 -->
              <roc-icon v-if="renderIcon" :size="16" :name="props.modelValue"></roc-icon>
            </template>
            <el-icon v-else :size="16"><search /></el-icon>
          </template>
        </el-input>
      </template>
      <!-- 选择图标 -->
      <div class="icon-content">
        <div class="icon-top-bar">
          <el-input
            v-model="filterIconName"
            placeholder="输入图标名称搜索"
            clearable
            @input="filterIcon"
            @clear="filterIcon"
          ></el-input>
          <el-button class="btn-clear-clone" @click="clearSelectedIcon">清除已选图标</el-button>
        </div>
        <div class="icon-list">
          <div class="icon-item" v-for="name in iconNameList" :key="name" @click="selectedIcon(name)">
            <roc-icon :name="name" :size="16"></roc-icon>
          </div>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup>
import iconNames from './requireIcons'
import { nextTick, ref } from 'vue'

const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: {
    type: String,
    required: true,
  },
})

const iconNameList = ref(iconNames)
const filterIconName = ref('')

/**
 * 过滤图标
 */
function filterIcon() {
  iconNameList.value = iconNames.filter((name) => name.includes(filterIconName.value))
}

const renderIcon = ref(true)
/**
 * 选择图标
 * @param {string} name
 */
async function selectedIcon(name) {
  // 解决 font 字体 icon 不刷新问题
  renderIcon.value = false
  await nextTick()
  renderIcon.value = true
  emit('update:modelValue', name)
  document.body.click()
}

/**
 * 清除已选图标
 */
function clearSelectedIcon() {
  emit('update:modelValue', name)
  document.body.click()
}
</script>

<style lang="scss" scoped>
.icon-content {
  height: 300px;
  overflow-y: auto;
  padding: 0 2px;
  .icon-top-bar {
    display: flex;
    margin-bottom: 6px;
    .btn-clear-clone {
      margin-left: 6px;
    }
  }
  .icon-list {
    display: flex;
    flex-wrap: wrap;
    .icon-item {
      width: 30px;
      height: 30px;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      .icon-name {
        font-size: 12px;
      }
    }
  }
}
</style>
